import * as fs from 'fs'
import * as path from 'path'

export class FileHelper {
	public static mkdirSync(filename: string) {
		if (!fs.existsSync(filename)) {
			fs.mkdirSync(filename, { recursive: true })
		}
	}

	public static removeAllFilesSync(dirname: string, fileExtension: string) {
		const files: fs.Dirent[] = FileHelper.readdirSync(dirname)

		files.forEach((file) => {
			if (file.name.endsWith(fileExtension)) {
				fs.unlinkSync(path.join(dirname, file.name))
			}
		})
	}

	public static removeFileSync(filename: string) {
		if (fs.existsSync(filename)) {
			fs.unlinkSync(filename)
		}
	}

	public static readdirSync(dirname: string): fs.Dirent[] {
		return fs.readdirSync(dirname, { withFileTypes: true })
	}

	public static readFileSync(filepath: string): string {
		return fs.readFileSync(filepath, 'utf8')
	}

	public static readJsonFileSync(filename: string) {
		const json = fs.readFileSync(filename, 'utf8')
		return JSON.parse(json)
	}

	public static rmdirSync(filename: string) {
		if (fs.existsSync(filename)) {
			fs.rmSync(filename, { recursive: true })
		}
	}

	public static writeFileSync(filepath: string, data: string) {
		fs.writeFileSync(filepath, data, 'utf8')
	}

	public static writeJsonFileSync(filename: string, data: any) {
		const parentDir = path.dirname(filename)
		if (!fs.existsSync(parentDir)) {
			fs.mkdirSync(parentDir, { recursive: true })
		}
		this.writeFileSync(filename, JSON.stringify(data, null, 2))
	}

	public static getResourceFile(...paths: string[]) {
		return path.join(path.dirname(__dirname), '../resources', ...paths)
	}

	public static getAppPath(...paths: string[]) {
		return path.join(path.dirname(__dirname), '..', ...paths)
	}
}
